<template>
  <!-- 采购合同报表首页 -->
  <div class="purchase_list">
    <div class="btns">
      <el-button type="primary" size="small" @click="batchImport">上传Excel<i class="el-icon-upload el-icon--right"></i></el-button>
      <el-input v-model="searchForm.purchaseContract" placeholder="采购合同"/>
      <el-input v-model="searchForm.name" placeholder="设备名"/>
      <el-input v-model="searchForm.model" placeholder="型号"/>
      <el-input v-model="searchForm.supplier" placeholder="供货商"/>
      <el-date-picker
        v-model="searchForm.time"
        unlink-panels
        value-format="timestamp"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-button type="primary" size="small" icon="el-icon-search" @click="toSearch">查询</el-button>
    </div>
    <el-card shadow="never">
      <a-table
        size = "small"
        :loading = "loading"
        :data-source = "purchaseData"
        :pagination = "pagination"
        :rowKey="record => record.id"
        :scroll="{x:2000}"
      >
        <a-table-column align="center" title="采购合同" ellipsis="true" key="purchaseContract" data-index="purchaseContract"/>
        <a-table-column align="center" title="设备名" ellipsis="true" key="name" data-index="name"/>
        <a-table-column align="center" title="型号" ellipsis="true" key="model" data-index="model"/>
        <a-table-column align="center" title="单位" ellipsis="true" key="unit" data-index="unit"/>
        <a-table-column align="center" title="数量" ellipsis="true" key="number" data-index="number"/>
        <a-table-column align="center" title="单价" ellipsis="true" key="price" data-index="price"/>
        <a-table-column align="center" title="总价" ellipsis="true" key="totalPrice" data-index="totalPrice">
          <template slot-scope="text,record">
            {{record.price*record.number}}
          </template>
        </a-table-column>
        <a-table-column align="center" title="供货商" ellipsis="true" key="supplier" data-index="supplier"/>
        <a-table-column align="center" title="签订日期" ellipsis="true" key="signData" data-index="signData"/>
        <a-table-column align="center" title="合同编号" ellipsis="true" key="no" data-index="no"/>
        <a-table-column align="center" title="合同总价" ellipsis="true" key="contractTotalPrice" data-index="contractTotalPrice"/>
        <a-table-column align="center" title="付款" ellipsis="true" key="paymentStatus" data-index="paymentStatus">
          <template slot-scope="text,record">
            <a-popover v-if="text!=null">
              <template #content>
                付款备注：{{record.paymentRemark}}<br>
              </template>
              <el-tag v-if="text == 0" :type="status[text]['type']">未付</el-tag>
              <el-tag v-if="text == 1" :type="status[text]['type']">已付</el-tag>
              <el-tag v-else-if="text == 2" :type="status[text]['type']">未付完</el-tag>
              <el-tag v-else-if="text == 3" :type="status[text]['type']">未知</el-tag>
            </a-popover>
          </template>
        </a-table-column>
        <a-table-column align="center" title="付款备注" ellipsis="true" key="paymentRemark" data-index="paymentRemark"/>
        <a-table-column align="center" title="对应合同" ellipsis="true" key="correspondSaleContract" data-index="correspondSaleContract"/>
        <a-table-column align="center" title="供货" ellipsis="true" key="supplyStatus" data-index="supplyStatus">
          <template slot-scope="text,record">
            <a-popover v-if="text!=null">
              <template #content>
                供货备注：{{record.supplyRemark}}<br>
              </template>
              <el-tag v-if="text == 0" :type="status[text]['type']">未供</el-tag>
              <el-tag v-if="text == 1" :type="status[text]['type']">已供</el-tag>
              <el-tag v-else-if="text == 2" :type="status[text]['type']">未供完</el-tag>
              <el-tag v-else-if="text == 3" :type="status[text]['type']">未知</el-tag>
            </a-popover>
          </template>
        </a-table-column>
        <a-table-column align="center" title="供货备注" ellipsis="true" key="supplyRemark" data-index="supplyRemark"/>
        <a-table-column align="center" title="发票" ellipsis="true" key="invoiceStatus" data-index="invoiceStatus">
          <template slot-scope="text,record">
            <a-popover v-if="text!=null">
              <template #content>
                发票备注：{{record.invoiceRemark}}<br>
              </template>
              <el-tag v-if="text == 0" :type="status[text]['type']">无</el-tag>
              <el-tag v-if="text == 1" :type="status[text]['type']">有</el-tag>
              <el-tag v-else-if="text == 2" :type="status[text]['type']">有部分</el-tag>
              <el-tag v-else-if="text == 3" :type="status[text]['type']">未知</el-tag>
            </a-popover>
          </template>
        </a-table-column>
        <a-table-column align="center" title="发票备注" ellipsis="true" key="invoiceRemark" data-index="invoiceRemark"/>
        <a-table-column align="center" title="到货" ellipsis="true" key="arrivalStatus" data-index="arrivalStatus">
          <template slot-scope="text,record">
            <a-popover v-if="text!=null">
              <template #content>
                到货备注：{{record.arrivalRemark}}<br>
              </template>
              <el-tag v-if="text == 0" :type="status[text]['type']">未到</el-tag>
              <el-tag v-if="text == 1" :type="status[text]['type']">已到</el-tag>
              <el-tag v-else-if="text == 2" :type="status[text]['type']">未到完</el-tag>
              <el-tag v-else-if="text == 3" :type="status[text]['type']">未知</el-tag>
            </a-popover>
          </template>
        </a-table-column>
        <a-table-column align="center" title="到货备注" ellipsis="true" key="arrivalRemark" data-index="arrivalRemark"/>
        <a-table-column align="center" title="合同约定到货时间" ellipsis="true" key="scheduledArrivalTime" data-index="scheduledArrivalTime"/>
        <a-table-column align="center" title="使用次数" ellipsis="true" key="usageTimes" data-index="usageTimes"/>
        <a-table-column align="center" title="操作" key="operation" width="100" fixed="right">
          <template slot-scope="text,record,index">
            <el-button type="primary" size="mini" @click="editData(record.id)">修改</el-button>
          </template>
        </a-table-column>
      </a-table>
    </el-card>



    <!-- 导入模态框 -->
    <el-dialog v-el-drag-dialog title="导入" :visible.sync="visible">
      <el-form status-icon>
        <el-button type="primary" size="small" @click="importDB"><a-icon type="file-excel" style="font-size: 12px;margin-right: 5px"/>导入</el-button>
        <input type="file" ref="upload" accept=".xls,.xlsx" @change="readExcel" class="outputlist_upload">
        <div v-if="excelRows>0" style="position: absolute;left: 0;padding: 4px 0;font-size: 12px;color: #909399">从Excel读取到
          <span style="color: #42b983">{{outputs.length}}</span>条数据
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelHandler2">取消</el-button>
        <el-button type="primary" :loading="submitLoading" size="small" @click="importHandler('form1')">提交</el-button>
      </div>
    </el-dialog>

    <!--修改模态框-->
    <el-dialog v-el-drag-dialog title="修改" :visible.sync="editVisible">
      <el-form status-icon ref="purchaseForm" :model="purchaseForm" :rules="rules" >
        <el-row :gutter="10">
          <el-col :lg="8" :sm="24">
            <el-form-item label="采购合同" label-width="80px" size="small" prop="purchaseContract">
              <el-input v-model="purchaseForm.purchaseContract" clearable placeholder="采购合同" size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :lg="8" :sm="24">
            <el-form-item label="付款" label-width="80px" size="small" prop="paymentStatus">
              <el-select v-model="purchaseForm.paymentStatus" placeholder="paymentStatus" size="small">
                <el-option v-for="item in [{0:'未付款'}, {1:'已付款'}, {2:'部分付款'}, {3:'未知'}]" :key="item" :value="item" :label="item"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelHandler1">取消</el-button>
        <el-button type="primary" :loading="submitLoading" size="small" @click="commitUpdate('form1')">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import "@/styles/auto-style.css";
  import {getAction, postActionByJson, postActionByQueryString} from "../../../api/manage";
  import XLSX from 'xlsx';
  import elDragDialog from '@/directive/el-drag-dialog'
  import request from '@/utils/request'

  export default{
      directives: { elDragDialog },
      data() {

          return {
              purchaseForm: {},
              editVisible: false,
              status: [
                  { type: 'danger', text: '0' },
                  { type: 'success', text: '1' },
                  { type: 'warning', text: '2' },
                  { type: 'info', text: '3' },
              ],
              submitLoading: false,
              visible: false,
              file: {},
              excelRows: 0,
              loading: true,
              purchaseData: [],
              searchForm: { time: []},
              url: {
                  selectByParams: '/report/selectByParams',
                  updateData: '/report/updateData',
                  deleteData: '/report/deleteData',
                  selectById: '/report/selectById'
              },
              pagination: {
                  showQuickJumper: true,
                  showSizeChanger: true,
                  pageSizeOptions: ['10', '20', '50'],
                  current: 1,
                  pageSize: 10,
                  total: 0,
                  onChange: (item) => {
                      this.pagination.current = item
                      this.loadingData()
                  },
                  showTotal: (total, range) => {
                      return range[0] + "-" + range[1] + " 共" + total + "条"
                  },
                  onShowSizeChange: (current, pageSize) => {
                      this.pagination.pageSize = pageSize
                      this.loadingData()
                  },
              },
          }
      },
      created() {
          this.loadingData()
      },
      methods: {
          commitUpdate(){

          },
          cancelHandler1(){
            this.editVisible = false
          },
          editData(id){
              if (id){

                getAction(this.url.selectById, {id: id})
                    .then(resp => {
                        this.purchaseForm = resp.data
                    })
                this.editVisible = true
              }
          },
          toSearch(){
              this.loadingData()
          },
          batchImport(){
              this.visible = true
          },
          importHandler() {
              if (this.file.id) {
                  this.submitLoading = true
                  request.request({
                      url: '/report/batchImportPurchase?fileId='+this.file.id+'',
                      method: 'get',
                      headers: {
                          'Content-Type': 'application/json'
                      },
                      // data: {fileId: this.file.id}
                  }).then( response => {
                      this.$message({ message: response.message, type: 'success' })
                      this.visible = false
                      this.submitLoading = false
                      this.loadingData()
                  }).catch(()=>{
                      this.submitLoading = false
                  })
              } else {
                  this.$message({ message: "文件上传解析中", type: 'warning' })
                  return false
              }
          },
          cancelHandler2() {
              this.visible = false
          },
          loadingData(){
              this.loading = true
              getAction(this.url.selectByParams, {
                  pageNo: this.pagination.current,
                  pageSize: this.pagination.pageSize,
                  name: this.searchForm.name,
                  purchaseContract: this.searchForm.purchaseContract,
                  model: this.searchForm.model,
                  supplier: this.searchForm.supplier,
                  startTime: this.searchForm.time[0],
                  endTime: this.searchForm.time[1]
              })
              .then(resp => {
                  setTimeout(()=>{
                      this.loading = false
                  },150)

                  this.purchaseData = resp.data.records
                  if (resp.data.total) {
                      this.pagination.current = resp.data.current
                      this.pagination.pageSize = resp.data.size
                      this.pagination.total = resp.data.total
                  }
              }).catch(()=>{
                  this.loading = false
              })
          },
          importDB(){
              this.$refs.upload.dispatchEvent(new MouseEvent('click'))
          },
          readExcel(e){
              var that = this;
              const files = e.target.files;

              if(files.length<=0){//如果没有文件名
                  return false
              }else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
                  this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
                  return false
              }

              const fileReader = new FileReader();
              this.excelRows = 0
              fileReader.onload = (ev) => {
                  try {
                      const data = ev.target.result;
                      const workbook = XLSX.read(data, {
                          type: 'binary'
                      });
                      const wsname = workbook.SheetNames[0];//取第一张表
                      const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容
                      console.log(ws)
                      that.outputs = [];//清空接收数据
                      ws.map(item => {
                          var num = Object.keys(item).length
                          console.log(item)
                          that.outputs.push(item);
                          this.excelRows ++
                      })
                      if(this.excelRows > 0){

                          let formData = new FormData();
                          formData.append('file', this.$refs.upload.files[0])
                          request.request({
                              url: '/file/uploadCache',
                              method: 'post',
                              headers: {
                                  'Content-Type': 'multipart/form-data'
                              },
                              data: formData
                          }).then(response => {
                              //this.$message({ message: response.message, type: '导入成功' })
                              this.file.id = response.fileId
                              //this.file.name = response.fileName
                              //this.file.url = response.url
                              console.info(this.file.id)
                          })
                      }
                      this.$refs.upload.value = '';
                  } catch (e) {
                      return false;
                  }
              };
              fileReader.readAsBinaryString(files[0]);
          }
      }

  }

</script>

<style lang="scss" scoped>

  .purchase_list{

  }
</style>
